package com.sy.pet.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.pet.commom.Fileutils;
import com.sy.pet.commom.enmu.ResponseCode;
import com.sy.pet.config.excetion.ServiceExcetion;
import com.sy.pet.dto.PetDTO;
import com.sy.pet.dto.PetQueryDTO;
import com.sy.pet.entity.PetInfo;
import com.sy.pet.entity.PetInfoTag;
import com.sy.pet.entity.PetTag;
import com.sy.pet.entity.PetType;
import com.sy.pet.mapper.PetInfoMapper;
import com.sy.pet.mapper.PetInfoTagMapper;
import com.sy.pet.vo.PetVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liangSY
 * @Date: 2024/9/14
 * @ClassName: PetInfoService
 * @Description: PetInfoService描述
 */
@Service
public class PetInfoService extends ServiceImpl<PetInfoMapper, PetInfo> {

    @Value("${pet.file-root-path}")
    private String fileRootPath;
    @Value("${pet.file-request-url}")
    private String fileRequestUrl;
    @Autowired
    PetInfoTagMapper petInfoTagMapper;

    public void add(PetDTO dto) {
        String fileStr = Fileutils.uploadFile(fileRootPath, dto.getCover(), "pet-info");
        PetInfo info = new PetInfo();
        info.setTitle(dto.getTitle());
        info.setNickname(dto.getNickName());
        info.setSex(dto.getSex());
        info.setIsActive(true);
        info.setStatus(false);
        info.setPetType(dto.getPetType());
        info.setCreateTime(LocalDateTime.now());
        info.setCover(fileStr);
        info.setDescription(dto.getDescription());
        baseMapper.insert(info);
        // 保存宠物标签
        if (StrUtil.isNotBlank(dto.getPetTag())) {
            String[] split = dto.getPetTag().split(",");
            for (String str : split) {
                petInfoTagMapper.insert(PetInfoTag.builder().petId(info.getId()).tagId(str).build());
            }
        }
    }

    public void update(PetDTO dto) {
        PetInfo petInfo = baseMapper.selectById(dto.getId());
        if (ObjectUtil.isEmpty(petInfo)) {
            throw new ServiceExcetion(ResponseCode.DATA_NOT_FOUND);
        }
        PetInfo info = new PetInfo();
        info.setTitle(dto.getTitle());
        info.setNickname(dto.getNickName());
        info.setSex(dto.getSex());
        info.setIsActive(true);
        info.setStatus(false);
        info.setPetType(dto.getPetType());
        info.setCreateTime(LocalDateTime.now());
        info.setDescription(dto.getDescription());
        if (!dto.getCover().isEmpty()) {
            String fileStr = Fileutils.uploadFile(fileRootPath, dto.getCover(), "pet-info");
            info.setCover(fileStr);
        }
        baseMapper.insert(info);
        // 移除宠物标签
        LambdaQueryWrapper<PetInfoTag> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PetInfoTag::getPetId, dto.getId());
        petInfoTagMapper.delete(queryWrapper);
        // 保存宠物标签
        if (StrUtil.isNotBlank(dto.getPetTag())) {
            String[] split = dto.getPetTag().split(",");
            for (String str : split) {
                petInfoTagMapper.insert(PetInfoTag.builder().petId(info.getId()).tagId(str).build());
            }
        }
    }

    public IPage<PetVO> getDataByPage(PetQueryDTO dto) {
        Page<PetVO> page = new Page(dto.getPage(), dto.getSize());
        IPage<PetVO> petInfoPage = baseMapper.findByPage(page, dto);
        petInfoPage.getRecords().stream().forEach(item -> {
            item.setCover(fileRequestUrl+item.getCover());
            item.setPetTag(getPetTage(item.getId()));
        });
        return petInfoPage;
    }

    public void remove(String id){
        PetInfo petInfo = baseMapper.selectById(id);
        if(Objects.isNull(petInfo)){
            throw new ServiceExcetion(ResponseCode.DATA_NOT_FOUND);
        }
        petInfo.setIsActive(false);
        baseMapper.updateById(petInfo);
    }

    private List<PetInfoTag> getPetTage(String id) {
        LambdaQueryWrapper<PetInfoTag> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PetInfoTag::getPetId, id);
        List<PetInfoTag> petInfoTags = petInfoTagMapper.selectList(queryWrapper);
        return petInfoTags;
    }
}
